import React, { useState } from 'react'
import address from '../address';
import { Form, Input, Button, Upload, PageHeader } from 'antd';
import { UploadOutlined } from '@ant-design/icons';

let token = '' || localStorage.getItem('token');


const normFile = (e) => {
    console.log('Upload event:', e);
    return e;
};


const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};



const AddApp = (props) => {

    const [title, setTitle] = useState('');
    const [fileList, setFileList] = useState([]);
    const [uploading, setUploading] = useState(false);

    const handleUpload = () => {

        const formData = new FormData();
        formData.append('cname', title);
        formData.append('image', fileList[0]);
        setUploading(true)

        let fileName = fileList[0].name.split('.')[0];
        let reg = /^[A-Za-z][A-Za-z0-9]+$/img;
        if (reg.test(fileName)) {
            fetch(address+'/admin/uploadapp', {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'authorization': token
                },
                body: formData
            }).then(res => {
                if (res.ok) {
                    setUploading(false);
                    //只有请求成功才会返回数据
                    return res.text();
                } else {
                    throw new Error(`status: ${res.status}`)
                }
            }, err => {
            }).then(d => {
                if (d === undefined || d === '') {
                    return
                }
                setUploading(false);
            })
                .catch(err => {
                    console.log(err)
                })
        } else {
            alert('文件名要求英文字母开头的字母和数字的组合！');
        }
    }

    const prop = {
        beforeUpload: file => {
            setFileList([...fileList, file])
            return false;
        },
    };


    return (
        <>
            <PageHeader
                className="site-page-header"
                subTitle="新增APP"
            />


            <Form
                {...layout}
                name="basic"
                initialValues={{ remember: true }}
                layout="vertical"
                style={{ marginLeft: '4%', marginTop: '2%' }}
            >
                <Form.Item
                    label="APP名称"
                    name="appname"
                    rules={[{ required: true, message: '请输入APP名称' }]}
                >
                    <Input value={title} onChange={e => setTitle(e.target.value)} />
                </Form.Item>


                <Form.Item
                    name="upload1"
                    label="APP图标"
                    valuePropName="fileList1"
                    getValueFromEvent={normFile}
                    extra="请选择APP图标"
                    rules={[{ required: true, message: '请选择APP图标' }]}
                >
                    <Upload {...prop}>
                        <Button icon={<UploadOutlined />}>选择图片</Button>
                    </Upload>
                </Form.Item>

                <Form.Item {...tailLayout}>
                    <Button
                        type="primary"
                        onClick={handleUpload}
                        // disabled={fileList.length === 0}
                        loading={uploading}
                        style={{ marginTop: 16 }}
                    >
                        {uploading ? '上传中...' : '上传'}
                    </Button>
                </Form.Item>
            </Form>

        </>
    )
}

export default AddApp
